package com.hongyun.tms.infra.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.hongyun.tms.common.constants.DefaultCreateByConstant;
import com.hongyun.tms.common.dto.mship.MShipImportDto;
import com.hongyun.tms.common.utils.MapperingUtils;
import com.hongyun.tms.entity.MShip;
import com.hongyun.tms.service.IMShipService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 船舶信息导入
 *
 * @author liPeng
 * @date 2024-09-10
 */
@Slf4j
@Component
public class MShipExcelListener extends DefaultExcelListener<MShipImportDto> {

    @Autowired
    private IMShipService shipService;

    public MShipExcelListener(IMShipService shipService) {
        this.shipService = shipService;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("成功读取excel中【" + getRows().size() + "】条船舶数据");

        // 获取读取的行数据并转为 MRateSaveReqDto 列表
        List<MShipImportDto> rows = getRows();
        List<MShip> mShips = MapperingUtils.copyList(rows, MShip.class);
        mShips.forEach((ship) -> {
            ship.setCreateTime(LocalDateTime.now());
            ship.setUpdateTime(LocalDateTime.now());
            ship.setCreateBy(DefaultCreateByConstant.userId);
            ship.setUpdateBy(DefaultCreateByConstant.userId);
            ship.setCreateByName(DefaultCreateByConstant.userId.toString());
            ship.setUpdateByName(DefaultCreateByConstant.userId.toString());
        });
        shipService.saveBatch(mShips);
        // 保存数据（可以进行批量插入）
        log.info("成功插入excel中【" + rows.size() + "】条船舶数据");
    }

}
